package com.token.sysflow.hander;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.token.base.JsonGenerator;
import com.token.base.Pl;
import com.token.sql.IntegrateSql;
import com.token.sql.PrepareSql;
import com.token.sysflow.bean.FSysFlowRecord;
import com.token.sysflow.bean.FlowFlowInfo;
import com.token.sysflow.enumerate.StepTypeEnum;
import com.token.sysflow.exception.ErrorCodeEnum;
import com.token.sysflow.exception.FlowException;
import com.token.sysorg.bean.FSysPersonnel;
import lombok.Getter;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author chenjianxiong 2020/5/12
 */
public class FlowRecord {
    private final FSysFlowRecord fSysFlowRecord;
    private final String keyUnid;

    @Getter
    private String flowId, stepId, stepName, approver;

    @Getter
    private int flowType;

    /**
     * @param iSql
     * @param keyUnid
     */
    public FlowRecord(IntegrateSql iSql, String keyUnid) {
        fSysFlowRecord = new FSysFlowRecord(iSql);
        this.keyUnid = keyUnid;
    }


    /**
     *
     */
    public void close() {
        try {
            fSysFlowRecord.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param fromStep
     * @param approver
     * @param flowType
     * @throws Exception
     */
    public void appendFlowRecord(Step fromStep, String approver, int flowType,String timer) throws Exception {
        fSysFlowRecord.setInsert();
        fSysFlowRecord.setKeyUnid(keyUnid); //单据关联
        fSysFlowRecord.setApprover(approver); //办理人账号ID
        fSysFlowRecord.setFlowId(fromStep.getFlowId()); //当前流程
        fSysFlowRecord.setStepId(fromStep.getStepId()); //当前环节
        fSysFlowRecord.setStepType(fromStep.getStepType()); //环节类型
        fSysFlowRecord.setStepName(fromStep.getStepName());
        fSysFlowRecord.setFlowType(flowType); //流程类型
        fSysFlowRecord.setSysAddTime(timer);
        fSysFlowRecord.executeUpdate();
    }

    /**
     * 获取开始环节
     *
     * @param flowId
     * @return
     * @throws Exception
     */
    public void setStartStep(String flowId) throws Exception {
        PrepareSql tSql = new PrepareSql(fSysFlowRecord.getIntegrateSql());
        tSql.setPrepare("select distinct FlowId,StepId,StepName,Approver,FlowType from F_Sys_FlowRecord where KeyUnid=? and StepType=? and flowId=?");
        tSql.setPstValue(1, keyUnid);
        tSql.setPstValue(2, StepTypeEnum.STEPTYPE_START.getTypeKey());
        tSql.setPstValue(3, flowId);
        ResultSet rs = tSql.executeQuery();
        if (rs.next()) {
            this.flowId = flowId;
            this.stepId = rs.getString("StepId");
            this.stepName = rs.getString("StepName");
            this.approver = rs.getString("Approver");
            this.flowType = rs.getInt("FlowType");
        } else {
            throw new FlowException(ErrorCodeEnum.FLOWRECORD_START_NOFIND_ERROR, this.keyUnid + " " + flowId);
        }
        rs.close();
        tSql.close();
    }

    /**
     * 历史审批环节
     *
     * @param jsonArray
     * @throws Exception
     */
    public void disFlowRecord(JSONArray jsonArray) throws Exception {
        LinkedHashMap<String,JSONObject> map = new LinkedHashMap<>();
        StringBuffer sql = new StringBuffer(100);
        sql.append("select f.flowId,stepId,stepName,approver,personName,flowType,flow.flowName")
                .append(" from ").append(fSysFlowRecord.getTableName())
                .append(" f inner join ").append(FSysPersonnel.TABLE_NAME).append(" user ")
                .append(" on f.Approver=user.PersonNumber and user.SysId=? ")
                .append(" inner join ").append(FlowFlowInfo.TABLE_NAME)
                .append(" flow on f.flowId=flow.flowId ")
                .append(" where keyUnid=? order by ").append(fSysFlowRecord.getKeyName());

        PrepareSql tSql = new PrepareSql(fSysFlowRecord.getIntegrateSql());
        tSql.setPrepare(sql);
        tSql.setPstValue(1, Pl.getSysId());
        tSql.setPstValue(2, keyUnid);
        ResultSet rs = tSql.executeQuery();
        if (rs.next()) {
            String stepId = rs.getString("StepId");
            ArrayList<String> array1 = new ArrayList<>();
            ArrayList<String> array2 = new ArrayList<>();
            JSONObject jsonObject = JsonGenerator.toJson(rs);
            jsonObject.put("approver",array1);
            jsonObject.put("personName",array2);
//            jsonArray.add(jsonObject);
            map.put(stepId,jsonObject);
//            System.out.println("---> " + rs.getString("stepName") + " " + rs.getString("stepId"));
//            Flow flow = new Flow(fSysFlowRecord.getIntegrateSql(),rs.getString("flowId"));
//            jsonObject.put("flowName",flow.getFlowName()+ " " + flow.getFlowVersion());
            do {
//                System.out.println("rs.getString(\"StepName\") = " + rs.getString("StepName"));

                if(!stepId.equals(rs.getString("StepId"))){
                    array1 = new ArrayList<>();
                    array2 = new ArrayList<>();
                    array1.add(rs.getString("Approver"));
                    array2.add(rs.getString("PersonName"));
                    jsonObject = JsonGenerator.toJson(rs);
                    jsonObject.put("approver",array1);
                    jsonObject.put("personName",array2);
//                    System.out.println("---> " + rs.getString("stepName") + " " + rs.getString("stepId"));
                    map.put(rs.getString("StepId"),jsonObject);
                }else{
                    array1.add(rs.getString("Approver"));
                    array2.add(rs.getString("PersonName"));
                }
                stepId = rs.getString("StepId");
            } while (rs.next());
        } else {
            throw new FlowException(ErrorCodeEnum.FLOWRECORD_NOFIND_ERROR, this.keyUnid);
        }
//        System.out.println("map = " + map);
        jsonArray.addAll(map.values());
        rs.close();
        tSql.close();
    }

    /**
     * 获取单据所有历史办理人包括起草人。
     *
     * @return List
     */
    public List<String> getFlowRecordApprovers() throws Exception {
        PrepareSql tSql = new PrepareSql(fSysFlowRecord.getIntegrateSql());
        tSql.setPrepare("select distinct Approver from F_Sys_FlowRecord where KeyUnid=? ");
        tSql.setPstValue(1, keyUnid);
        ResultSet rs = tSql.executeQuery();
        List<String> arrayList = new ArrayList<>();
        if (rs.next()) {
            do {
                arrayList.add(rs.getString("Approver"));
            } while (rs.next());
        } else {
            throw new FlowException(ErrorCodeEnum.FLOWRECORD_NOFIND_ERROR, this.keyUnid);
        }
        rs.close();
        tSql.close();
        return arrayList;
    }
//
//    /**
//     * 获取指定环节单据历史办理人。
//     *
//     * @return List
//     */
//    public JSONArray getFlowRecordApprovers(String stepId) throws Exception {
//
//        PrepareSql tSql = new PrepareSql(fSysFlowRecord.getIntegrateSql());
//        tSql.setPrepare("select distinct Approver from F_Sys_FlowRecord where KeyUnid=? and StepId=? ");
//        tSql.setPstValue(1,keyUnid);
//        tSql.setPstValue(2,stepId);
//        ResultSet rs = tSql.executeQuery();
//        StringBuffer user = new StringBuffer(100);
//        if (rs.next()) {
//            boolean isHas = false;
//            do {
//                if(isHas){
//                    user.append(",");
//                }
//                user.append("'").append(rs.getString("Approver")).append("'");
//                isHas = true;
//            } while (rs.next());
//            rs.close();
//        } else {
//            throw new FlowException(ErrorCodeEnum.FLOWRECORD_NOFIND_ERROR, this.keyUnid+"," + stepId);
//        }
//
//        JSONArray array = getUserData(user,Pl.getSysId());
//        tSql.close();
//        return array;
//    }
//
//    /**
//     *
//     * @param user
//     * @param SysId
//     * @return
//     * @throws Exception
//     */
//    public JSONArray getUserData(StringBuffer user,int SysId) throws Exception{
//        JSONArray array = new JSONArray();
//        StringBuffer sql = new StringBuffer(100);
//        sql.append("select user.PersonNumber as id,user.PersonName as name,post.PostName from ")
//                .append(FSysPersonnel.TABLE_NAME)
//                .append(" user left join ")
//                .append(FSysPost.TABLE_NAME)
//                .append(" post on user.PostId=post.PostNumber and user.SysId=post.SysId ");
//        sql.append("where user.SysId=? and user.PersionNumber in(").append(user).append(")");
//        PrepareSql pSql = new PrepareSql(fSysFlowRecord.getIntegrateSql());
//        pSql.setPrepare(sql);
//        pSql.setPstValue(1,SysId);
//        ResultSet rs = pSql.executeQuery();
//        if(rs.next()){
//            JSONObject jsonObject= new JSONObject();
//            jsonObject.put("postName",rs.getString("PostName"));
//            jsonObject.put("name",rs.getString("PersonName"));
//            jsonObject.put("checked",true);
//            jsonObject.put("id",rs.getString("id"));
//            jsonObject.put("isHas",true);
//            array.add(jsonObject);
//        }
//        return array;
//    }
}
